/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../database.ts" />
/// <reference path="./connection.ts" />

namespace lcc {

const mysql = require("mysql");

const TAG = "lcc/database/mysql/database.ts";

/**
 * @zh
 * Mysql 数据库配置
 * 详情查看 https://www.npmjs.com/package/mysql
 */
export interface MysqlDatabaseConfig {
	host?:string;
	port?:number;
	localAddress?:string;
	socketPath?:string;
	user?:string;
	password?:string;
	database?:string;
	charset?:string;
	timezone?:string;
	connectTimeout?:number;
	stringifyObjects?:boolean;
	insecureAuth?:boolean;
	typeCast?:boolean;
	queryFormat?:Function;
	supportBigNumbers?:boolean;
	bigNumberStrings?:boolean;
	dateStrings?:boolean;
	debug?:boolean;
	trace?:boolean;
	localInfile?:boolean;
	multipleStatements?:boolean;
	flags?:string;
	ssl?:{
		ca?:string;
		rejectUnauthorized?:boolean;
	};
}

/**
 * @zh
 * Mysql 数据库
 */
export class MysqlDatabase extends Database {

	/**
     * @zh
	 * 配置
	 */
	private _config:MysqlDatabaseConfig = null;
	
    /**
     * @zh
     * 连接池
     */
	private _pool:any = null;
	
	/**
     * @zh
	 * 配置数据库
     * 
	 * @param config - 配置对象
	 */
	public config(config:MysqlDatabaseConfig){
		this._config = config;
	}
	
	/**
     * @zh
	 * 连接数据库
	 */
	public async connect(){
		if(!this._pool){
			this._pool = mysql.createPool(this._config);
        }
        return true;
	}

	/**
     * @zh
	 * 断开数据库
	 */
	public async disconnect(){
		if(this._pool){
			this._pool.end();
			this._pool = null;
		}
        return true;
	}
	
	/**
     * @zh
	 * 获得连接
	 */
	public async getConnection(){
		return new Promise<MysqlConnection>((resole)=>{
			DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} getConnection`);
			if(!this._pool){
				resole(null);
			}else{
				this._pool.getConnection((error, con)=>{
					if(error){
						logMgr.error(TAG, `${this.getName()} getConnection error ${error}`);
						resole(null);
					}else{
						DEBUG.DATABASE && logMgr.debug(TAG, `${this.getName()} getConnection true`);
						let connection = new MysqlConnection(this);
						connection.config({ con : con });
						resole(connection);
					}
				});
			}
		});
	}
}

// 注册数据库类型
dbMgr.registerDatabaseType(DatabaseType.MYSQL, MysqlDatabase);

}
